<?php
// 本类由系统自动生成，仅供测试用途
namespace Home\Controller;
use Think\Controller;
class WeixinController extends Controller {


/**
*接口
*/


public function https_post($url,$data=null){
	$curl=curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	if(!empty($data)){
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$output=curl_exec($curl);
	curl_close($curl);
	return $output;

}

/**
*微信生成二维码 
*/
public function generate_code(){
	$access_token=$this->getWxAccessToken();
	//临时二维码
	$qrcode='{"expire_seconds":1800,"action_name":"QR_SCENE","action_info":{"scene":{"scene_id":1000}}}';
	//永久二维码
	$qrcode_yj="";
	$url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
	$result=$this->https_post($url,$qrcode);
	$jsoninfo=json_decode($result,true);
	$ticket=$jsoninfo["ticket"];
	$url="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;
	echo "<img src='".$url."'/>";
	var_dump($ticket);
}


/**
* 获取token方法
*/
public function getWxAccessToken(){
	$appid='wx2eba7aba580e31af';
	$appsecret='0c5b6572fecaa37bf292d76d174bff11';
	$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
	$res=$this->https_post($url);
	$jsoninfo=json_decode($res,true);
	$access_token=$jsoninfo['access_token'];
	return $access_token;
}


/**
*定义微信菜单
*/
public function definedItem(){
	$access_token=$this->getWxAccessToken();
	$url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
	

	$jsonmenu = '{
      "button":[
	
	{	
          "type":"click",
          "name":"今日歌曲",
          "key":"V1001_TODAY_MUSIC"
      },
       
      {	    
	   
            "name":"天气预报",
           "sub_button":[
            {
               "type":"click",
               "name":"北京天气",
               "key":"天气北京"
            },
            {
               "type":"click",
               "name":"上海天气",
               "key":"天气上海"
            },
            {
               "type":"click",
               "name":"广州天气",
               "key":"天气广州"
            },
            {
               "type":"click",
               "name":"深圳天气",
               "key":"天气深圳"
            },
            {
                "type":"view",
                "name":"本地天气",
                "url":"http://m.hao123.com/a/tianqi"
            }]
      

       },
       {
           "name":"方倍工作室",
           "sub_button":[
            {
               "type":"click",
               "name":"公司简介",
               "key":"company"
            },
            {
               "type":"click",
               "name":"趣味游戏",
               "key":"游戏"
            },
            {
                "type":"click",
                "name":"讲个笑话",
                "key":"笑话"
            }]
       

       }

       }
]
 }';

	$postArr=array(
		'button'=>array(
				array(
					'name'=>urlencode('菜单一'),
					'type'=>'click',
					'key'=>'item1',
				),
				array(
					'name'=>urlencode('菜单二'),
					'sub_button'=>array(
							array(
								'name'=>urlencode('歌曲'),
								'type'=>'click',
								'key'=>'songs',
							),//第一个菜单
							array(
								'name'=>urlencode('电影'),
								'type'=>'view',
								'url'=>"http://www.baidu.com",
							),//第二个二级菜单
						),
					),
				array(
					'name'=>urlencode('菜单三'),
					'type'=>'view',
					'url'=>"http://www.baidu.com"
					)
			),
		);
	$postJson=urldecode(json_encode($postArr));
	$result=$this->https_post($url,$postJson);
//	var_dump($postJson);
	//var_dump($result);
}

/**
*发送模板消息
*/
public function template_message($data){
	$access_token=$this->getWxAccessToken();
	$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
	// echo $url;
	var_dump($data);
	$send_message='{
						   "touser":"'.$data['user_openid'].'",
						   "template_id":"CErXn6kzkhUaaE6R9NDcbWtdyTDdluxbOxp-oMfBp6c",
						   "url":"http://dadouyundong.com/",            
						   "data":{
									"title": {
									   "value":"'.$data['user_name'].'\n",
									   "color":"#000000"
								   },
									"content": {
									   "value":"您的'.$data['user_st'].'已有人下单",
									   "color":"#173177"
								   },
								   "time": {
									   "value":"下单时间'.$data['user_ordertime'].'",
									   "color":"#173177"
								   }
								   }
							   }';
							   var_dump($send_message);
	$send_arr=$this->https_post($url,$send_message);
	$jsoninfo=json_decode($send_arr,true);
	// var_dump($jsoninfo);

}
//没实现

public function upload_photo(){
	$access_token=$this->getWxAccessToken();
	$url="https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=".$access_token;
	$photo_url='{
   "articles": [
		 {
             "thumb_media_id":"qI6_Ze_6PtV7svjolgs-rN6stStuHIjs9_DidOHaj0Q-mwvBelOXCFZiq2OsIU-p",
             "author":"xxx",
			 "title":"Happy Day",
			 "content_source_url":"www.qq.com",
			 "content":"content",
			 "digest":"digest",
                        "show_cover_pic":"1"
		 },
		 {
                        "thumb_media_id":"qI6_Ze_6PtV7svjolgs-rN6stStuHIjs9_DidOHaj0Q-mwvBelOXCFZiq2OsIU-p",
                        "author":"xxx",
			 "title":"Happy Day",
			 "content_source_url":"www.qq.com",
			 "content":"content",
			 "digest":"digest",
                        "show_cover_pic":"0"
		 }
   ]
}';
	$image=$this->https_post($url,$photo_url);
	var_dump($image);
}


/**
*每分钟执行一次判断，是则发送模板消息
*/

public function remind_user(){
		//$this->remind_message($openid,$info,$res);
		ignore_user_abort(); // //关掉浏览器，PHP脚本也可以继续执行.
		set_time_limit(0); // 通过set_time_limit(0)可以让程序无限制的执行下去
		$interval=60; // do every 15 minutes...
		$i=0;
		do{
		 
			template_message();

			sleep($interval); // wait 15 minutes
 
		}while(true);
		
}

// function index(){
// 	$nonce=$_GET['nonce'];
// 	$token=getWxAccessToken();
// 	///$token='imooc';
// 	$timestamp=$_GET['timestamp'];
// 	$echostr=$_GET['echostr'];
// 	$siguature=$_GET['siguature'];
// 	$array=array();
// 	$array=array($nonce,$timestamp,$token);
// 	sort($array);
// 	$str=sha1(implode($array));
// 	if($str==$siguature){
// 		echo $echostr;
// 		exit;
// 	}else{
// 		template_message();
// 	}

// }

/**
*下载二维码图片的方法 下载到根目录中
*/
public function down_qrcode(){
	$access_token=$this->getWxAccessToken();
	//临时二维码 public
	$qrcode='{"expire_seconds":1800,"action_name":"QR_SCENE","action_info":{"scene":{"scene_id":1000}}}';
	//永久二维码
	$qrcode_yj="";
	$url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
	$result=https_post($url,$qrcode);
	$jsoninfo=json_decode($result,true);
	$ticket=$jsoninfo["ticket"];
	$url="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);
	echo "<img src='".$url."'/>";



	$imageInfo=downloadImageFromWeiXin($url);
	$file_iamge="qrcode.jpg";
	$local_file=fopen($file_iamge, 'w');
	if(false!==$local_file){
		if(false!==fwrite($local_file, $imageInfo["body"])){
			fclose($local_file);
		}
	}

}
/**
*下载二维码图片的执行方法 
*/
public function downloadImageFromWeiXin($url){
	$ch=curl_init($url);
	curl_setopt($ch,CURLOPT_HEADER, 0);
	curl_setopt($ch,CURLOPT_NOBODY,0);
	curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	$package=curl_exec($ch);
	$httpinfo=curl_getinfo($ch);
	curl_close($ch);
	return array_merge(array('body'=>$package),array('header'=>$httpinfo));

}

// function reponseMsg(){
// 	$postArr=$GLOBALS['HTTP_RAW_POST_DATA'];
// 	$postObj=simplexml_load_string($postArr);
// 	if(strtolower($postObj->MsgType)=='event'){
// 		if(strtolower($postObj->Event=='subscribe')){
// 			$arr=array(
// 					array(

// 						)
// 				)
// 		}

// 	}
// }

public function receiveEvent($object)
{
    $contentStr = "";
    switch ($object->Event)
    {
        case "subscribe":
            $contentStr = "欢迎关注 ";
            if (isset($object->EventKey)){
                $contentStr = "关注二维码场景 ".$object->EventKey;
            }
            break;
        case "SCAN":
            $contentStr = "扫描 ".$object->EventKey;
            break;
        default:
            break;      
 
    }
    $resultStr = $this->transmitText($object, $contentStr);
    return $resultStr;
}

// public function getJsApiTicket(){
// 	$access_token = $this->getWxAccessToken();
// 	$jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
// 	$jsapi_ticket = $this->https_post($jsapi_ticket_url);
// 	$arr_jsapi_ticket = json_decode($jsapi_ticket,true);
// 	return $arr_jsapi_ticket['ticket'];
// }

public function getRandcode($num=16){
	$array = array(
			'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T',
			'U','V','W','X','Y','Z',
			'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t',
			'u','v','w','x','y','z',
			'0','1','2','3','4','5','6','7','8','9'
		);
	$tmpstr = '';
	$max = count($array);
	for($i = 1;$i<=16;$i++){
		$key = rand(0,$max-1);
		$tmpstr .=$array[$key];
	}
	return $tmpstr;

}

public function index(){
	// https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
	//获取jsapi_ticket
	$jsapiTicket = $this->getJsApiTicket();
	$timestamp = time();
	$noncestr = $this->getRandcode();
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	//$url = 'http://zhangzj.cn/weixin_interface.php';
    // $signature = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
	// $signature = 'jsapi_ticket='.$jsapiTicket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;
	$signature = "jsapi_ticket=".$jsapiTicket."&noncestr=".$noncestr."&timestamp=".$timestamp."&url=".$url;	
	$signature = sha1($signature);
	$this->assign('name','zzj');
	$this->assign('timestamp',$timestamp);
	$this->assign('noncestr',$noncestr);
	$this->assign('signature',$signature);
	$this->display();
}




 private function getJsApiTicket() {
    // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
    $data = json_decode(file_get_contents("jsapi_ticket.json"));
    if ($data->expire_time < time()) {
      $accessToken = $this->getWxAccessToken();
      // var_dump($accessToken);die;
      // 如果是企业号用以下 URL 获取 ticket
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
      $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
      $res = json_decode($this->https_post($url));
      $ticket = $res->ticket;
      if ($ticket) {
        $data->expire_time = time() + 7000;
        $data->jsapi_ticket = $ticket;
        $fp = fopen("jsapi_ticket.json", "w");
        fwrite($fp, json_encode($data));
        fclose($fp);
      }
    } else {
      $ticket = $data->jsapi_ticket;
    }

    return $ticket;
  }


/*
*网页授权
*获取用户的openid
*/
  public function get_base_info()
  {
  	$appid = 'wx2eba7aba580e31af';
  	$redirect_uri = urlencode('http://www.zhangzj.cn/weixin/index.php/Home/Weixin/get_userOpenid');
  	//获取code
  	$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
  	//获取网页授权的accessToken
  	// echo $url;
  	header('location:'.$url);

  }

  public function get_userOpenid()
  {
  	$appid = 'wx2eba7aba580e31af';
  	$appsecret = '0c5b6572fecaa37bf292d76d174bff11';
  	$code = $_GET['code'];
  	$Url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
  	$res = $this -> https_post($Url,'get');
  	var_dump($res);
  	die;
  	// if($res['access_token']){

  	// }
  }
}
